package org.groupg.calcite;

import org.apache.calcite.adapter.java.ReflectiveSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.groupg.model.CustInfo;
import org.groupg.model.OrgInfo;
import org.groupg.model.UserInfo;

import java.sql.*;
import java.util.Properties;

public class DemoSchema {
    public static class HrSchema {
        public final CustInfo[] custs = {};
        public final UserInfo[] users = {};
        public final OrgInfo[] orgs = {};
    }

    public static void main(String[] args) {
        try {
            Class.forName("org.apache.calcite.jdbc.Driver");

        Properties info = new Properties();
//        info.setProperty("lex", "JAVA");
        Connection connection =
                DriverManager.getConnection("jdbc:calcite:", info);
        CalciteConnection calciteConnection =
                connection.unwrap(CalciteConnection.class);
        SchemaPlus rootSchema = calciteConnection.getRootSchema();
        Schema schema = new ReflectiveSchema(new HrSchema());
        rootSchema.add("hr", schema);
        Statement statement = calciteConnection.createStatement();
        ResultSet resultSet = statement.executeQuery(
                "select a.orgname,count(c.userid)\n" +
                        "from hr.orgs a \n" +
                        "    left join hr.users u on a.orgid = u.orgid \n" +
                        "    left join hr.custs c on u.userid = c.userid\n" +
                        "group by a.orgname");
        System.out.print(resultSet);
        resultSet.close();
        statement.close();
        connection.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
